package com.example.springboot11.controller;

import com.example.springboot11.entity.User;
import com.example.springboot11.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/index")
    public String index() {
        System.out.println("这是主页");
        return "index";
    }

    @GetMapping("/login")
    public String login() {

        return "login";
    }

    @PostMapping("/login")
    public String toLogin(@RequestParam("name") String username, String password, HttpServletRequest request, HttpServletResponse response) {
        try {
            String token=userService.authentication(username, password);
            String user = userService.authentication(username, password);
            Cookie cookie = new Cookie("token", username);
            cookie.setMaxAge(5*60);
            response.addCookie(cookie);
            request.setAttribute("user",username);
            return "index";
        } catch (Exception e) {
            request.setAttribute("error", "用户名不存在或密码错误");
            return "login";

        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie=new Cookie("token","");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        request.removeAttribute("user");
        return "redirect:/index";
    }

}